home *** CD-ROM | disk | FTP | other *** search
/ Programming Languages Suite / ProgramD2.iso / Database Designers / Rational Rose 2000 / Rational Setup.EXE / common / lib / overload.pm < prev    next >
Text File  |  1999-01-25  |  40KB  |  1,217 lines

  1. package overload;
  2.  
  3. sub nil {}
  4.  
  5. sub OVERLOAD {
  6.   $package = shift;
  7.   my %arg = @_;
  8.   my ($sub, $fb);
  9.   $ {$package . "::OVERLOAD"}{dummy}++; # Register with magic by touching.
  10.   *{$package . "::()"} = \&nil; # Make it findable via fetchmethod.
  11.   for (keys %arg) {
  12.     if ($_ eq 'fallback') {
  13.       $fb = $arg{$_};
  14.     } else {
  15.       $sub = $arg{$_};
  16.       if (not ref $sub and $sub !~ /::/) {
  17.     $ {$package . "::(" . $_} = $sub;
  18.     $sub = \&nil;
  19.       }
  20.       #print STDERR "Setting `$ {'package'}::\cO$_' to \\&`$sub'.\n";
  21.       *{$package . "::(" . $_} = \&{ $sub };
  22.     }
  23.   }
  24.   ${$package . "::()"} = $fb; # Make it findable too (fallback only).
  25. }
  26.  
  27. sub import {
  28.   $package = (caller())[0];
  29.   # *{$package . "::OVERLOAD"} = \&OVERLOAD;
  30.   shift;
  31.   $package->overload::OVERLOAD(@_);
  32. }
  33.  
  34. sub unimport {
  35.   $package = (caller())[0];
  36.   ${$package . "::OVERLOAD"}{dummy}++; # Upgrade the table
  37.   shift;
  38.   for (@_) {
  39.     if ($_ eq 'fallback') {
  40.       undef $ {$package . "::()"};
  41.     } else {
  42.       delete $ {$package . "::"}{"(" . $_};
  43.     }
  44.   }
  45. }
  46.  
  47. sub Overloaded {
  48.   my $package = shift;
  49.   $package = ref $package if ref $package;
  50.   $package->can('()');
  51. }
  52.  
  53. sub ov_method {
  54.   my $globref = shift;
  55.   return undef unless $globref;
  56.   my $sub = \&{*$globref};
  57.   return $sub if $sub ne \&nil;
  58.   return shift->can($ {*$globref});
  59. }
  60.  
  61. sub OverloadedStringify {
  62.   my $package = shift;
  63.   $package = ref $package if ref $package;
  64.   #$package->can('(""')
  65.   ov_method mycan($package, '(""'), $package
  66.     or ov_method mycan($package, '(0+'), $package
  67.     or ov_method mycan($package, '(bool'), $package
  68.     or ov_method mycan($package, '(nomethod'), $package;
  69. }
  70.  
  71. sub Method {
  72.   my $package = shift;
  73.   $package = ref $package if ref $package;
  74.   #my $meth = $package->can('(' . shift);
  75.   ov_method mycan($package, '(' . shift), $package;
  76.   #return $meth if $meth ne \&nil;
  77.   #return $ {*{$meth}};
  78. }
  79.  
  80. sub AddrRef {
  81.   my $package = ref $_[0];
  82.   return "$_[0]" unless $package;
  83.   bless $_[0], overload::Fake;    # Non-overloaded package
  84.   my $str = "$_[0]";
  85.   bless $_[0], $package;    # Back
  86.   $package . substr $str, index $str, '=';
  87. }
  88.  
  89. sub StrVal {
  90.   (OverloadedStringify($_[0])) ?
  91.     (AddrRef(shift)) :
  92.     "$_[0]";
  93. }
  94.  
  95. sub mycan {                # Real can would leave stubs.
  96.   my ($package, $meth) = @_;
  97.   return \*{$package . "::$meth"} if defined &{$package . "::$meth"};
  98.   my $p;
  99.   foreach $p (@{$package . "::ISA"}) {
  100.     my $out = mycan($p, $meth);
  101.     return $out if $out;
  102.   }
  103.   return undef;
  104. }
  105.  
  106. %constants = (
  107.           'integer'      =>  0x1000, 
  108.           'float'      =>  0x2000,
  109.           'binary'      =>  0x4000,
  110.           'q'      =>  0x8000,
  111.           'qr'      => 0x10000,
  112.          );
  113.  
  114. %ops = ( with_assign      => "+ - * / % ** << >> x .",
  115.      assign          => "+= -= *= /= %= **= <<= >>= x= .=",
  116.      str_comparison      => "< <= >  >= == !=",
  117.      '3way_comparison'=> "<=> cmp",
  118.      num_comparison      => "lt le gt ge eq ne",
  119.      binary          => "& | ^",
  120.      unary          => "neg ! ~",
  121.      mutators      => '++ --',
  122.      func          => "atan2 cos sin exp abs log sqrt",
  123.      conversion      => 'bool "" 0+',
  124.      special      => 'nomethod fallback =');
  125.  
  126. sub constant {
  127.   # Arguments: what, sub
  128.   while (@_) {
  129.     $^H{$_[0]} = $_[1];
  130.     $^H |= $constants{$_[0]} | 0x20000;
  131.     shift, shift;
  132.   }
  133. }
  134.  
  135. sub remove_constant {
  136.   # Arguments: what, sub
  137.   while (@_) {
  138.     delete $^H{$_[0]};
  139.     $^H &= ~ $constants{$_[0]};
  140.     shift, shift;
  141.   }
  142. }
  143.  
  144. 1;
  145.  
  146. __END__
  147.  
  148. =head1 NAME 
  149.  
  150. overload - Package for overloading perl operations
  151.  
  152. =head1 SYNOPSIS
  153.  
  154.     package SomeThing;
  155.  
  156.     use overload 
  157.     '+' => \&myadd,
  158.     '-' => \&mysub;
  159.     # etc
  160.     ...
  161.  
  162.     package main;
  163.     $a = new SomeThing 57;
  164.     $b=5+$a;
  165.     ...
  166.     if (overload::Overloaded $b) {...}
  167.     ...
  168.     $strval = overload::StrVal $b;
  169.  
  170. =head1 CAVEAT SCRIPTOR
  171.  
  172. Overloading of operators is a subject not to be taken lightly.
  173. Neither its precise implementation, syntax, nor semantics are
  174. 100% endorsed by Larry Wall.  So any of these may be changed 
  175. at some point in the future.
  176.  
  177. =head1 DESCRIPTION
  178.  
  179. =head2 Declaration of overloaded functions
  180.  
  181. The compilation directive
  182.  
  183.     package Number;
  184.     use overload
  185.     "+" => \&add, 
  186.     "*=" => "muas";
  187.  
  188. declares function Number::add() for addition, and method muas() in
  189. the "class" C<Number> (or one of its base classes)
  190. for the assignment form C<*=> of multiplication.  
  191.  
  192. Arguments of this directive come in (key, value) pairs.  Legal values
  193. are values legal inside a C<&{ ... }> call, so the name of a
  194. subroutine, a reference to a subroutine, or an anonymous subroutine
  195. will all work.  Note that values specified as strings are
  196. interpreted as methods, not subroutines.  Legal keys are listed below.
  197.  
  198. The subroutine C<add> will be called to execute C<$a+$b> if $a
  199. is a reference to an object blessed into the package C<Number>, or if $a is
  200. not an object from a package with defined mathemagic addition, but $b is a
  201. reference to a C<Number>.  It can also be called in other situations, like
  202. C<$a+=7>, or C<$a++>.  See L<MAGIC AUTOGENERATION>.  (Mathemagical
  203. methods refer to methods triggered by an overloaded mathematical
  204. operator.)
  205.  
  206. Since overloading respects inheritance via the @ISA hierarchy, the
  207. above declaration would also trigger overloading of C<+> and C<*=> in
  208. all the packages which inherit from C<Number>.
  209.  
  210. =head2 Calling Conventions for Binary Operations
  211.  
  212. The functions specified in the C<use overload ...> directive are called
  213. with three (in one particular case with four, see L<Last Resort>)
  214. arguments.  If the corresponding operation is binary, then the first
  215. two arguments are the two arguments of the operation.  However, due to
  216. general object calling conventions, the first argument should always be
  217. an object in the package, so in the situation of C<7+$a>, the
  218. order of the arguments is interchanged.  It probably does not matter
  219. when implementing the addition method, but whether the arguments
  220. are reversed is vital to the subtraction method.  The method can
  221. query this information by examining the third argument, which can take
  222. three different values:
  223.  
  224. =over 7
  225.  
  226. =item FALSE
  227.  
  228. the order of arguments is as in the current operation.
  229.  
  230. =item TRUE
  231.  
  232. the arguments are reversed.
  233.  
  234. =item C<undef>
  235.  
  236. the current operation is an assignment variant (as in
  237. C<$a+=7>), but the usual function is called instead.  This additional
  238. information can be used to generate some optimizations.  Compare
  239. L<Calling Conventions for Mutators>.
  240.  
  241. =back
  242.  
  243. =head2 Calling Conventions for Unary Operations
  244.  
  245. Unary operation are considered binary operations with the second
  246. argument being C<undef>.  Thus the functions that overloads C<{"++"}>
  247. is called with arguments C<($a,undef,'')> when $a++ is executed.
  248.  
  249. =head2 Calling Conventions for Mutators
  250.  
  251. Two types of mutators have different calling conventions:
  252.  
  253. =over
  254.  
  255. =item C<++> and C<-->
  256.  
  257. The routines which implement these operators are expected to actually
  258. I<mutate> their arguments.  So, assuming that $obj is a reference to a
  259. number,
  260.  
  261.   sub incr { my $n = $ {$_[0]}; ++$n; $_[0] = bless \$n}
  262.  
  263. is an appropriate implementation of overloaded C<++>.  Note that
  264.  
  265.   sub incr { ++$ {$_[0]} ; shift }
  266.  
  267. is OK if used with preincrement and with postincrement. (In the case
  268. of postincrement a copying will be performed, see L<Copy Constructor>.)
  269.  
  270. =item C<x=> and other assignment versions
  271.  
  272. There is nothing special about these methods.  They may change the
  273. value of their arguments, and may leave it as is.  The result is going
  274. to be assigned to the value in the left-hand-side if different from
  275. this value.
  276.  
  277. This allows for the same method to be used as averloaded C<+=> and
  278. C<+>.  Note that this is I<allowed>, but not recommended, since by the
  279. semantic of L<"Fallback"> Perl will call the method for C<+> anyway,
  280. if C<+=> is not overloaded.
  281.  
  282. =back
  283.  
  284. B<Warning.>  Due to the presense of assignment versions of operations,
  285. routines which may be called in assignment context may create 
  286. self-referencial structures.  Currently Perl will not free self-referential 
  287. structures until cycles are C<explicitly> broken.  You may get problems
  288. when traversing your structures too.
  289.  
  290. Say, 
  291.  
  292.   use overload '+' => sub { bless [ \$_[0], \$_[1] ] };
  293.  
  294. is asking for trouble, since for code C<$obj += $foo> the subroutine
  295. is called as C<$obj = add($obj, $foo, undef)>, or C<$obj = [\$obj, 
  296. \$foo]>.  If using such a subroutine is an important optimization, one
  297. can overload C<+=> explicitly by a non-"optimized" version, or switch
  298. to non-optimized version if C<not defined $_[2]> (see 
  299. L<Calling Conventions for Binary Operations>).
  300.  
  301. Even if no I<explicit> assignment-variants of operators are present in
  302. the script, they may be generated by the optimizer.  Say, C<",$obj,"> or
  303. C<',' . $obj . ','> may be both optimized to
  304.  
  305.   my $tmp = ',' . $obj;    $tmp .= ',';
  306.  
  307. =head2 Overloadable Operations
  308.  
  309. The following symbols can be specified in C<use overload> directive:
  310.  
  311. =over 5
  312.  
  313. =item * I<Arithmetic operations>
  314.  
  315.     "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
  316.     "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
  317.  
  318. For these operations a substituted non-assignment variant can be called if
  319. the assignment variant is not available.  Methods for operations "C<+>",
  320. "C<->", "C<+=>", and "C<-=>" can be called to automatically generate
  321. increment and decrement methods.  The operation "C<->" can be used to
  322. autogenerate missing methods for unary minus or C<abs>.
  323.  
  324. See L<"MAGIC AUTOGENERATION">, L<"Calling Conventions for Mutators"> and
  325. L<"Calling Conventions for Binary Operations">) for details of these
  326. substitutions.
  327.  
  328. =item * I<Comparison operations>
  329.  
  330.     "<",  "<=", ">",  ">=", "==", "!=", "<=>",
  331.     "lt", "le", "gt", "ge", "eq", "ne", "cmp",
  332.  
  333. If the corresponding "spaceship" variant is available, it can be
  334. used to substitute for the missing operation.  During C<sort>ing
  335. arrays, C<cmp> is used to compare values subject to C<use overload>.
  336.  
  337. =item * I<Bit operations>
  338.  
  339.     "&", "^", "|", "neg", "!", "~",
  340.  
  341. "C<neg>" stands for unary minus.  If the method for C<neg> is not
  342. specified, it can be autogenerated using the method for
  343. subtraction. If the method for "C<!>" is not specified, it can be
  344. autogenerated using the methods for "C<bool>", or "C<\"\">", or "C<0+>".
  345.  
  346. =item * I<Increment and decrement>
  347.  
  348.     "++", "--",
  349.  
  350. If undefined, addition and subtraction methods can be
  351. used instead.  These operations are called both in prefix and
  352. postfix form.
  353.  
  354. =item * I<Transcendental functions>
  355.  
  356.     "atan2", "cos", "sin", "exp", "abs", "log", "sqrt",
  357.  
  358. If C<abs> is unavailable, it can be autogenerated using methods
  359. for "E<lt>" or "E<lt>=E<gt>" combined with either unary minus or subtraction.
  360.  
  361. =item * I<Boolean, string and numeric conversion>
  362.  
  363.     "bool", "\"\"", "0+",
  364.  
  365. If one or two of these operations are unavailable, the remaining ones can
  366. be used instead.  C<bool> is used in the flow control operators
  367. (like C<while>) and for the ternary "C<?:>" operation.  These functions can
  368. return any arbitrary Perl value.  If the corresponding operation for this value
  369. is overloaded too, that operation will be called again with this value.
  370.  
  371. =item * I<Special>
  372.  
  373.     "nomethod", "fallback", "=",
  374.  
  375. see L<SPECIAL SYMBOLS FOR C<use overload>>.
  376.  
  377. =back
  378.  
  379. See L<"Fallback"> for an explanation of when a missing method can be
  380. autogenerated.
  381.  
  382. A computer-readable form of the above table is available in the hash
  383. %overload::ops, with values being space-separated lists of names:
  384.  
  385.  with_assign      => '+ - * / % ** << >> x .',
  386.  assign          => '+= -= *= /= %= **= <<= >>= x= .=',
  387.  str_comparison      => '< <= > >= == !=',
  388.  '3way_comparison'=> '<=> cmp',
  389.  num_comparison      => 'lt le gt ge eq ne',
  390.  binary          => '& | ^',
  391.  unary          => 'neg ! ~',
  392.  mutators      => '++ --',
  393.  func          => 'atan2 cos sin exp abs log sqrt',
  394.  conversion      => 'bool "" 0+',
  395.  special      => 'nomethod fallback ='
  396.  
  397. =head2 Inheritance and overloading
  398.  
  399. Inheritance interacts with overloading in two ways.
  400.  
  401. =over
  402.  
  403. =item Strings as values of C<use overload> directive
  404.  
  405. If C<value> in
  406.  
  407.   use overload key => value;
  408.  
  409. is a string, it is interpreted as a method name.
  410.  
  411. =item Overloading of an operation is inherited by derived classes
  412.  
  413. Any class derived from an overloaded class is also overloaded.  The
  414. set of overloaded methods is the union of overloaded methods of all
  415. the ancestors. If some method is overloaded in several ancestor, then
  416. which description will be used is decided by the usual inheritance
  417. rules:
  418.  
  419. If C<A> inherits from C<B> and C<C> (in this order), C<B> overloads
  420. C<+> with C<\&D::plus_sub>, and C<C> overloads C<+> by C<"plus_meth">,
  421. then the subroutine C<D::plus_sub> will be called to implement
  422. operation C<+> for an object in package C<A>.
  423.  
  424. =back
  425.  
  426. Note that since the value of the C<fallback> key is not a subroutine,
  427. its inheritance is not governed by the above rules.  In the current
  428. implementation, the value of C<fallback> in the first overloaded
  429. ancestor is used, but this is accidental and subject to change.
  430.  
  431. =head1 SPECIAL SYMBOLS FOR C<use overload>
  432.  
  433. Three keys are recognized by Perl that are not covered by the above
  434. description.
  435.  
  436. =head2 Last Resort
  437.  
  438. C<"nomethod"> should be followed by a reference to a function of four
  439. parameters.  If defined, it is called when the overloading mechanism
  440. cannot find a method for some operation.  The first three arguments of
  441. this function coincide with the arguments for the corresponding method if
  442. it were found, the fourth argument is the symbol
  443. corresponding to the missing method.  If several methods are tried,
  444. the last one is used.  Say, C<1-$a> can be equivalent to
  445.  
  446.     &nomethodMethod($a,1,1,"-")
  447.  
  448. if the pair C<"nomethod" =E<gt> "nomethodMethod"> was specified in the
  449. C<use overload> directive.
  450.  
  451. If some operation cannot be resolved, and there is no function
  452. assigned to C<"nomethod">, then an exception will be raised via die()--
  453. unless C<"fallback"> was specified as a key in C<use overload> directive.
  454.  
  455. =head2 Fallback 
  456.  
  457. The key C<"fallback"> governs what to do if a method for a particular
  458. operation is not found.  Three different cases are possible depending on
  459. the value of C<"fallback">:
  460.  
  461. =over 16
  462.  
  463. =item * C<undef>
  464.  
  465. Perl tries to use a
  466. substituted method (see L<MAGIC AUTOGENERATION>).  If this fails, it
  467. then tries to calls C<"nomethod"> value; if missing, an exception
  468. will be raised.
  469.  
  470. =item * TRUE
  471.  
  472. The same as for the C<undef> value, but no exception is raised.  Instead,
  473. it silently reverts to what it would have done were there no C<use overload>
  474. present.
  475.  
  476. =item * defined, but FALSE
  477.  
  478. No autogeneration is tried.  Perl tries to call
  479. C<"nomethod"> value, and if this is missing, raises an exception. 
  480.  
  481. =back
  482.  
  483. B<Note.> C<"fallback"> inheritance via @ISA is not carved in stone
  484. yet, see L<"Inheritance and overloading">.
  485.  
  486. =head2 Copy Constructor
  487.  
  488. The value for C<"="> is a reference to a function with three
  489. arguments, i.e., it looks like the other values in C<use
  490. overload>. However, it does not overload the Perl assignment
  491. operator. This would go against Camel hair.
  492.  
  493. This operation is called in the situations when a mutator is applied
  494. to a reference that shares its object with some other reference, such
  495. as
  496.  
  497.     $a=$b; 
  498.     ++$a;
  499.  
  500. To make this change $a and not change $b, a copy of C<$$a> is made,
  501. and $a is assigned a reference to this new object.  This operation is
  502. done during execution of the C<++$a>, and not during the assignment,
  503. (so before the increment C<$$a> coincides with C<$$b>).  This is only
  504. done if C<++> is expressed via a method for C<'++'> or C<'+='> (or
  505. C<nomethod>).  Note that if this operation is expressed via C<'+'>
  506. a nonmutator, i.e., as in
  507.  
  508.     $a=$b; 
  509.     $a=$a+1;
  510.  
  511. then C<$a> does not reference a new copy of C<$$a>, since $$a does not
  512. appear as lvalue when the above code is executed.
  513.  
  514. If the copy constructor is required during the execution of some mutator,
  515. but a method for C<'='> was not specified, it can be autogenerated as a
  516. string copy if the object is a plain scalar.
  517.  
  518. =over 5
  519.  
  520. =item B<Example>
  521.  
  522. The actually executed code for 
  523.  
  524.     $a=$b; 
  525.         Something else which does not modify $a or $b....
  526.     ++$a;
  527.  
  528. may be
  529.  
  530.     $a=$b; 
  531.         Something else which does not modify $a or $b....
  532.     $a = $a->clone(undef,"");
  533.         $a->incr(undef,"");
  534.  
  535. if $b was mathemagical, and C<'++'> was overloaded with C<\&incr>,
  536. C<'='> was overloaded with C<\&clone>.
  537.  
  538. =back
  539.  
  540. Same behaviour is triggered by C<$b = $a++>, which is consider a synonim for
  541. C<$b = $a; ++$a>.
  542.  
  543. =head1 MAGIC AUTOGENERATION
  544.  
  545. If a method for an operation is not found, and the value for  C<"fallback"> is
  546. TRUE or undefined, Perl tries to autogenerate a substitute method for
  547. the missing operation based on the defined operations.  Autogenerated method
  548. substitutions are possible for the following operations:
  549.  
  550. =over 16
  551.  
  552. =item I<Assignment forms of arithmetic operations>
  553.  
  554. C<$a+=$b> can use the method for C<"+"> if the method for C<"+=">
  555. is not defined.
  556.  
  557. =item I<Conversion operations> 
  558.  
  559. String, numeric, and boolean conversion are calculated in terms of one
  560. another if not all of them are defined.
  561.  
  562. =item I<Increment and decrement>
  563.  
  564. The C<++$a> operation can be expressed in terms of C<$a+=1> or C<$a+1>,
  565. and C<$a--> in terms of C<$a-=1> and C<$a-1>.
  566.  
  567. =item C<abs($a)>
  568.  
  569. can be expressed in terms of C<$aE<lt>0> and C<-$a> (or C<0-$a>).
  570.  
  571. =item I<Unary minus>
  572.  
  573. can be expressed in terms of subtraction.
  574.  
  575. =item I<Negation>
  576.  
  577. C<!> and C<not> can be expressed in terms of boolean conversion, or
  578. string or numerical conversion.
  579.  
  580. =item I<Concatenation>
  581.  
  582. can be expressed in terms of string conversion.
  583.  
  584. =item I<Comparison operations> 
  585.  
  586. can be expressed in terms of its "spaceship" counterpart: either
  587. C<E<lt>=E<gt>> or C<cmp>:
  588.  
  589.     <, >, <=, >=, ==, !=     in terms of <=>
  590.     lt, gt, le, ge, eq, ne     in terms of cmp
  591.  
  592. =item I<Copy operator>
  593.  
  594. can be expressed in terms of an assignment to the dereferenced value, if this
  595. value is a scalar and not a reference.
  596.  
  597. =back
  598.  
  599. =head1 Losing overloading
  600.  
  601. The restriction for the comparison operation is that even if, for example,
  602. `C<cmp>' should return a blessed reference, the autogenerated `C<lt>'
  603. function will produce only a standard logical value based on the
  604. numerical value of the result of `C<cmp>'.  In particular, a working
  605. numeric conversion is needed in this case (possibly expressed in terms of
  606. other conversions).
  607.  
  608. Similarly, C<.=>  and C<x=> operators lose their mathemagical properties
  609. if the string conversion substitution is applied.
  610.  
  611. When you chop() a mathemagical object it is promoted to a string and its
  612. mathemagical properties are lost.  The same can happen with other
  613. operations as well.
  614.  
  615. =head1 Run-time Overloading
  616.  
  617. Since all C<use> directives are executed at compile-time, the only way to
  618. change overloading during run-time is to
  619.  
  620.     eval 'use overload "+" => \&addmethod';
  621.  
  622. You can also use
  623.  
  624.     eval 'no overload "+", "--", "<="';
  625.  
  626. though the use of these constructs during run-time is questionable.
  627.  
  628. =head1 Public functions
  629.  
  630. Package C<overload.pm> provides the following public functions:
  631.  
  632. =over 5
  633.  
  634. =item overload::StrVal(arg)
  635.  
  636. Gives string value of C<arg> as in absence of stringify overloading.
  637.  
  638. =item overload::Overloaded(arg)
  639.  
  640. Returns true if C<arg> is subject to overloading of some operations.
  641.  
  642. =item overload::Method(obj,op)
  643.  
  644. Returns C<undef> or a reference to the method that implements C<op>.
  645.  
  646. =back
  647.  
  648. =head1 Overloading constants
  649.  
  650. For some application Perl parser mangles constants too much.  It is possible
  651. to hook into this process via overload::constant() and overload::remove_constant()
  652. functions.
  653.  
  654. These functions take a hash as an argument.  The recognized keys of this hash
  655. are
  656.  
  657. =over 8
  658.  
  659. =item integer
  660.  
  661. to overload integer constants,
  662.  
  663. =item float
  664.  
  665. to overload floating point constants,
  666.  
  667. =item binary
  668.  
  669. to overload octal and hexadecimal constants,
  670.  
  671. =item q
  672.  
  673. to overload C<q>-quoted strings, constant pieces of C<qq>- and C<qx>-quoted
  674. strings and here-documents,
  675.  
  676. =item qr
  677.  
  678. to overload constant pieces of regular expressions.
  679.  
  680. =back
  681.  
  682. The corresponding values are references to functions which take three arguments:
  683. the first one is the I<initial> string form of the constant, the second one
  684. is how Perl interprets this constant, the third one is how the constant is used.  
  685. Note that the initial string form does not
  686. contain string delimiters, and has backslashes in backslash-delimiter 
  687. combinations stripped (thus the value of delimiter is not relevant for
  688. processing of this string).  The return value of this function is how this 
  689. constant is going to be interpreted by Perl.  The third argument is undefined
  690. unless for overloaded C<q>- and C<qr>- constants, it is C<q> in single-quote
  691. context (comes from strings, regular expressions, and single-quote HERE
  692. documents), it is C<tr> for arguments of C<tr>/C<y> operators, 
  693. it is C<s> for right-hand side of C<s>-operator, and it is C<qq> otherwise.
  694.  
  695. Since an expression C<"ab$cd,,"> is just a shortcut for C<'ab' . $cd . ',,'>,
  696. it is expected that overloaded constant strings are equipped with reasonable
  697. overloaded catenation operator, otherwise absurd results will result.  
  698. Similarly, negative numbers are considered as negations of positive constants.
  699.  
  700. Note that it is probably meaningless to call the functions overload::constant()
  701. and overload::remove_constant() from anywhere but import() and unimport() methods.
  702. From these methods they may be called as
  703.  
  704.     sub import {
  705.       shift;
  706.       return unless @_;
  707.       die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
  708.       overload::constant integer => sub {Math::BigInt->new(shift)};
  709.     }
  710.  
  711. B<BUGS> Currently overloaded-ness of constants does not propagate 
  712. into C<eval '...'>.
  713.  
  714. =head1 IMPLEMENTATION
  715.  
  716. What follows is subject to change RSN.
  717.  
  718. The table of methods for all operations is cached in magic for the
  719. symbol table hash for the package.  The cache is invalidated during
  720. processing of C<use overload>, C<no overload>, new function
  721. definitions, and changes in @ISA. However, this invalidation remains
  722. unprocessed until the next C<bless>ing into the package. Hence if you
  723. want to change overloading structure dynamically, you'll need an
  724. additional (fake) C<bless>ing to update the table.
  725.  
  726. (Every SVish thing has a magic queue, and magic is an entry in that
  727. queue.  This is how a single variable may participate in multiple
  728. forms of magic simultaneously.  For instance, environment variables
  729. regularly have two forms at once: their %ENV magic and their taint
  730. magic. However, the magic which implements overloading is applied to
  731. the stashes, which are rarely used directly, thus should not slow down
  732. Perl.)
  733.  
  734. If an object belongs to a package using overload, it carries a special
  735. flag.  Thus the only speed penalty during arithmetic operations without
  736. overloading is the checking of this flag.
  737.  
  738. In fact, if C<use overload> is not present, there is almost no overhead
  739. for overloadable operations, so most programs should not suffer
  740. measurable performance penalties.  A considerable effort was made to
  741. minimize the overhead when overload is used in some package, but the
  742. arguments in question do not belong to packages using overload.  When
  743. in doubt, test your speed with C<use overload> and without it.  So far
  744. there have been no reports of substantial speed degradation if Perl is
  745. compiled with optimization turned on.
  746.  
  747. There is no size penalty for data if overload is not used. The only
  748. size penalty if overload is used in some package is that I<all> the
  749. packages acquire a magic during the next C<bless>ing into the
  750. package. This magic is three-words-long for packages without
  751. overloading, and carries the cache tabel if the package is overloaded.
  752.  
  753. Copying (C<$a=$b>) is shallow; however, a one-level-deep copying is 
  754. carried out before any operation that can imply an assignment to the
  755. object $a (or $b) refers to, like C<$a++>.  You can override this
  756. behavior by defining your own copy constructor (see L<"Copy Constructor">).
  757.  
  758. It is expected that arguments to methods that are not explicitly supposed
  759. to be changed are constant (but this is not enforced).
  760.  
  761. =head1 Metaphor clash
  762.  
  763. One may wonder why the semantic of overloaded C<=> is so counterintuive.
  764. If it I<looks> counterintuive to you, you are subject to a metaphor 
  765. clash.  
  766.  
  767. Here is a Perl object metaphor:
  768.  
  769. I<  object is a reference to blessed data>
  770.  
  771. and an arithmetic metaphor:
  772.  
  773. I<  object is a thing by itself>.
  774.  
  775. The I<main> problem of overloading C<=> is the fact that these metaphors
  776. imply different actions on the assignment C<$a = $b> if $a and $b are
  777. objects.  Perl-think implies that $a becomes a reference to whatever
  778. $b was referencing.  Arithmetic-think implies that the value of "object"
  779. $a is changed to become the value of the object $b, preserving the fact
  780. that $a and $b are separate entities.
  781.  
  782. The difference is not relevant in the absence of mutators.  After
  783. a Perl-way assignment an operation which mutates the data referenced by $a
  784. would change the data referenced by $b too.  Effectively, after 
  785. C<$a = $b> values of $a and $b become I<indistinguishable>.
  786.  
  787. On the other hand, anyone who has used algebraic notation knows the 
  788. expressive power of the arithmetic metaphor.  Overloading works hard
  789. to enable this metaphor while preserving the Perlian way as far as
  790. possible.  Since it is not not possible to freely mix two contradicting
  791. metaphors, overloading allows the arithmetic way to write things I<as
  792. far as all the mutators are called via overloaded access only>.  The
  793. way it is done is described in L<Copy Constructor>.
  794.  
  795. If some mutator methods are directly applied to the overloaded values,
  796. one may need to I<explicitly unlink> other values which references the 
  797. same value:
  798.  
  799.     $a = new Data 23;
  800.     ...
  801.     $b = $a;        # $b is "linked" to $a
  802.     ...
  803.     $a = $a->clone;    # Unlink $b from $a
  804.     $a->increment_by(4);
  805.  
  806. Note that overloaded access makes this transparent:
  807.  
  808.     $a = new Data 23;
  809.     $b = $a;        # $b is "linked" to $a
  810.     $a += 4;        # would unlink $b automagically
  811.  
  812. However, it would not make
  813.  
  814.     $a = new Data 23;
  815.     $a = 4;        # Now $a is a plain 4, not 'Data'
  816.  
  817. preserve "objectness" of $a.  But Perl I<has> a way to make assignments
  818. to an object do whatever you want.  It is just not the overload, but
  819. tie()ing interface (see L<perlfunc/tie>).  Adding a FETCH() method
  820. which returns the object itself, and STORE() method which changes the 
  821. value of the object, one can reproduce the arithmetic metaphor in its
  822. completeness, at least for variables which were tie()d from the start.
  823.  
  824. (Note that a workaround for a bug may be needed, see L<"BUGS">.)
  825.  
  826. =head1 Cookbook
  827.  
  828. Please add examples to what follows!
  829.  
  830. =head2 Two-face scalars
  831.  
  832. Put this in F<two_face.pm> in your Perl library directory:
  833.  
  834.   package two_face;        # Scalars with separate string and
  835.                                 # numeric values.
  836.   sub new { my $p = shift; bless [@_], $p }
  837.   use overload '""' => \&str, '0+' => \&num, fallback => 1;
  838.   sub num {shift->[1]}
  839.   sub str {shift->[0]}
  840.  
  841. Use it as follows:
  842.  
  843.   require two_face;
  844.   my $seven = new two_face ("vii", 7);
  845.   printf "seven=$seven, seven=%d, eight=%d\n", $seven, $seven+1;
  846.   print "seven contains `i'\n" if $seven =~ /i/;
  847.  
  848. (The second line creates a scalar which has both a string value, and a
  849. numeric value.)  This prints:
  850.  
  851.   seven=vii, seven=7, eight=8
  852.   seven contains `i'
  853.  
  854. =head2 Symbolic calculator
  855.  
  856. Put this in F<symbolic.pm> in your Perl library directory:
  857.  
  858.   package symbolic;        # Primitive symbolic calculator
  859.   use overload nomethod => \&wrap;
  860.  
  861.   sub new { shift; bless ['n', @_] }
  862.   sub wrap {
  863.     my ($obj, $other, $inv, $meth) = @_;
  864.     ($obj, $other) = ($other, $obj) if $inv;
  865.     bless [$meth, $obj, $other];
  866.   }
  867.  
  868. This module is very unusual as overloaded modules go: it does not
  869. provide any usual overloaded operators, instead it provides the L<Last
  870. Resort> operator C<nomethod>.  In this example the corresponding
  871. subroutine returns an object which encupsulates operations done over
  872. the objects: C<new symbolic 3> contains C<['n', 3]>, C<2 + new
  873. symbolic 3> contains C<['+', 2, ['n', 3]]>.
  874.  
  875. Here is an example of the script which "calculates" the side of
  876. circumscribed octagon using the above package:
  877.  
  878.   require symbolic;
  879.   my $iter = 1;            # 2**($iter+2) = 8
  880.   my $side = new symbolic 1;
  881.   my $cnt = $iter;
  882.   
  883.   while ($cnt--) {
  884.     $side = (sqrt(1 + $side**2) - 1)/$side;
  885.   }
  886.   print "OK\n";
  887.  
  888. The value of $side is
  889.  
  890.   ['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]],
  891.                    undef], 1], ['n', 1]]
  892.  
  893. Note that while we obtained this value using a nice little script,
  894. there is no simple way to I<use> this value.  In fact this value may
  895. be inspected in debugger (see L<perldebug>), but ony if
  896. C<bareStringify> B<O>ption is set, and not via C<p> command.
  897.  
  898. If one attempts to print this value, then the overloaded operator
  899. C<""> will be called, which will call C<nomethod> operator.  The
  900. result of this operator will be stringified again, but this result is
  901. again of type C<symbolic>, which will lead to an infinite loop.
  902.  
  903. Add a pretty-printer method to the module F<symbolic.pm>:
  904.  
  905.   sub pretty {
  906.     my ($meth, $a, $b) = @{+shift};
  907.     $a = 'u' unless defined $a;
  908.     $b = 'u' unless defined $b;
  909.     $a = $a->pretty if ref $a;
  910.     $b = $b->pretty if ref $b;
  911.     "[$meth $a $b]";
  912.   } 
  913.  
  914. Now one can finish the script by
  915.  
  916.   print "side = ", $side->pretty, "\n";
  917.  
  918. The method C<pretty> is doing object-to-string conversion, so it
  919. is natural to overload the operator C<""> using this method.  However,
  920. inside such a method it is not necessary to pretty-print the
  921. I<components> $a and $b of an object.  In the above subroutine
  922. C<"[$meth $a $b]"> is a catenation of some strings and components $a
  923. and $b.  If these components use overloading, the catenation operator
  924. will look for an overloaded operator C<.>, if not present, it will
  925. look for an overloaded operator C<"">.  Thus it is enough to use
  926.  
  927.   use overload nomethod => \&wrap, '""' => \&str;
  928.   sub str {
  929.     my ($meth, $a, $b) = @{+shift};
  930.     $a = 'u' unless defined $a;
  931.     $b = 'u' unless defined $b;
  932.     "[$meth $a $b]";
  933.   } 
  934.  
  935. Now one can change the last line of the script to
  936.  
  937.   print "side = $side\n";
  938.  
  939. which outputs
  940.  
  941.   side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]
  942.  
  943. and one can inspect the value in debugger using all the possible
  944. methods.  
  945.  
  946. Something is is still amiss: consider the loop variable $cnt of the
  947. script.  It was a number, not an object.  We cannot make this value of
  948. type C<symbolic>, since then the loop will not terminate.
  949.  
  950. Indeed, to terminate the cycle, the $cnt should become false.
  951. However, the operator C<bool> for checking falsity is overloaded (this
  952. time via overloaded C<"">), and returns a long string, thus any object
  953. of type C<symbolic> is true.  To overcome this, we need a way to
  954. compare an object to 0.  In fact, it is easier to write a numeric
  955. conversion routine.
  956.  
  957. Here is the text of F<symbolic.pm> with such a routine added (and
  958. slightly modifed str()):
  959.  
  960.   package symbolic;        # Primitive symbolic calculator
  961.   use overload
  962.     nomethod => \&wrap, '""' => \&str, '0+' => \#
  963.  
  964.   sub new { shift; bless ['n', @_] }
  965.   sub wrap {
  966.     my ($obj, $other, $inv, $meth) = @_;
  967.     ($obj, $other) = ($other, $obj) if $inv;
  968.     bless [$meth, $obj, $other];
  969.   }
  970.   sub str {
  971.     my ($meth, $a, $b) = @{+shift};
  972.     $a = 'u' unless defined $a;
  973.     if (defined $b) {
  974.       "[$meth $a $b]";
  975.     } else {
  976.       "[$meth $a]";
  977.     }
  978.   } 
  979.   my %subr = ( n => sub {$_[0]}, 
  980.            sqrt => sub {sqrt $_[0]}, 
  981.            '-' => sub {shift() - shift()},
  982.            '+' => sub {shift() + shift()},
  983.            '/' => sub {shift() / shift()},
  984.            '*' => sub {shift() * shift()},
  985.            '**' => sub {shift() ** shift()},
  986.          );
  987.   sub num {
  988.     my ($meth, $a, $b) = @{+shift};
  989.     my $subr = $subr{$meth} 
  990.       or die "Do not know how to ($meth) in symbolic";
  991.     $a = $a->num if ref $a eq __PACKAGE__;
  992.     $b = $b->num if ref $b eq __PACKAGE__;
  993.     $subr->($a,$b);
  994.   }
  995.  
  996. All the work of numeric conversion is done in %subr and num().  Of
  997. course, %subr is not complete, it contains only operators used in teh
  998. example below.  Here is the extra-credit question: why do we need an
  999. explicit recursion in num()?  (Answer is at the end of this section.)
  1000.  
  1001. Use this module like this:
  1002.  
  1003.   require symbolic;
  1004.   my $iter = new symbolic 2;    # 16-gon
  1005.   my $side = new symbolic 1;
  1006.   my $cnt = $iter;
  1007.   
  1008.   while ($cnt) {
  1009.     $cnt = $cnt - 1;        # Mutator `--' not implemented
  1010.     $side = (sqrt(1 + $side**2) - 1)/$side;
  1011.   }
  1012.   printf "%s=%f\n", $side, $side;
  1013.   printf "pi=%f\n", $side*(2**($iter+2));
  1014.  
  1015. It prints (without so many line breaks)
  1016.  
  1017.   [/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1]
  1018.               [n 1]] 2]]] 1]
  1019.      [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912
  1020.   pi=3.182598
  1021.  
  1022. The above module is very primitive.  It does not implement
  1023. mutator methods (C<++>, C<-=> and so on), does not do deep copying
  1024. (not required without mutators!), and implements only those arithmetic
  1025. operations which are used in the example.
  1026.  
  1027. To implement most arithmetic operattions is easy, one should just use
  1028. the tables of operations, and change the code which fills %subr to
  1029.  
  1030.   my %subr = ( 'n' => sub {$_[0]} );
  1031.   foreach my $op (split " ", $overload::ops{with_assign}) {
  1032.     $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
  1033.   }
  1034.   my @bins = qw(binary 3way_comparison num_comparison str_comparison);
  1035.   foreach my $op (split " ", "@overload::ops{ @bins }") {
  1036.     $subr{$op} = eval "sub {shift() $op shift()}";
  1037.   }
  1038.   foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
  1039.     print "defining `$op'\n";
  1040.     $subr{$op} = eval "sub {$op shift()}";
  1041.   }
  1042.  
  1043. Due to L<Calling Conventions for Mutators>, we do not need anything
  1044. special to make C<+=> and friends work, except filling C<+=> entry of
  1045. %subr, and defining a copy constructor (needed since Perl has no
  1046. way to know that the implementation of C<'+='> does not mutate
  1047. the argument, compare L<Copy Constructor>).
  1048.  
  1049. To implement a copy constructor, add C<'=' => \&cpy> to C<use overload>
  1050. line, and code (this code assumes that mutators change things one level
  1051. deep only, so recursive copying is not needed):
  1052.  
  1053.   sub cpy {
  1054.     my $self = shift;
  1055.     bless [@$self], ref $self;
  1056.   }
  1057.  
  1058. To make C<++> and C<--> work, we need to implement actual mutators, 
  1059. either directly, or in C<nomethod>.  We continue to do things inside
  1060. C<nomethod>, thus add
  1061.  
  1062.     if ($meth eq '++' or $meth eq '--') {
  1063.       @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
  1064.       return $obj;
  1065.     }
  1066.  
  1067. after the first line of wrap().  This is not a most effective 
  1068. implementation, one may consider
  1069.  
  1070.   sub inc { $_[0] = bless ['++', shift, 1]; }
  1071.  
  1072. instead.
  1073.  
  1074. As a final remark, note that one can fill %subr by
  1075.  
  1076.   my %subr = ( 'n' => sub {$_[0]} );
  1077.   foreach my $op (split " ", $overload::ops{with_assign}) {
  1078.     $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
  1079.   }
  1080.   my @bins = qw(binary 3way_comparison num_comparison str_comparison);
  1081.   foreach my $op (split " ", "@overload::ops{ @bins }") {
  1082.     $subr{$op} = eval "sub {shift() $op shift()}";
  1083.   }
  1084.   foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
  1085.     $subr{$op} = eval "sub {$op shift()}";
  1086.   }
  1087.   $subr{'++'} = $subr{'+'};
  1088.   $subr{'--'} = $subr{'-'};
  1089.  
  1090. This finishes implementation of a primitive symbolic calculator in 
  1091. 50 lines of Perl code.  Since the numeric values of subexpressions 
  1092. are not cached, the calculator is very slow.
  1093.  
  1094. Here is the answer for the exercise: In the case of str(), we need no
  1095. explicit recursion since the overloaded C<.>-operator will fall back
  1096. to an existing overloaded operator C<"">.  Overloaded arithmetic
  1097. operators I<do not> fall back to numeric conversion if C<fallback> is
  1098. not explicitly requested.  Thus without an explicit recursion num()
  1099. would convert C<['+', $a, $b]> to C<$a + $b>, which would just rebuild
  1100. the argument of num().
  1101.  
  1102. If you wonder why defaults for conversion are different for str() and
  1103. num(), note how easy it was to write the symbolic calculator.  This
  1104. simplicity is due to an appropriate choice of defaults.  One extra
  1105. note: due to teh explicit recursion num() is more fragile than sym():
  1106. we need to explicitly check for the type of $a and $b.  If componets
  1107. $a and $b happen to be of some related type, this may lead to problems.
  1108.  
  1109. =head2 I<Really> symbolic calculator
  1110.  
  1111. One may wonder why we call the above calculator symbolic.  The reason
  1112. is that the actual calculation of the value of expression is postponed
  1113. until the value is I<used>.
  1114.  
  1115. To see it in action, add a method
  1116.  
  1117.   sub STORE { 
  1118.     my $obj = shift; 
  1119.     $#$obj = 1; 
  1120.     @$obj->[0,1] = ('=', shift);
  1121.   }
  1122.  
  1123. to the package C<symbolic>.  After this change one can do
  1124.  
  1125.   my $a = new symbolic 3;
  1126.   my $b = new symbolic 4;
  1127.   my $c = sqrt($a**2 + $b**2);
  1128.  
  1129. and the numeric value of $c becomes 5.  However, after calling
  1130.  
  1131.   $a->STORE(12);  $b->STORE(5);
  1132.  
  1133. the numeric value of $c becomes 13.  There is no doubt now that the module
  1134. symbolic provides a I<symbolic> calculator indeed.
  1135.  
  1136. To hide the rough edges under the hood, provide a tie()d interface to the
  1137. package C<symbolic> (compare with L<Metaphor clash>).  Add methods
  1138.  
  1139.   sub TIESCALAR { my $pack = shift; $pack->new(@_) }
  1140.   sub FETCH { shift }
  1141.   sub nop {  }        # Around a bug
  1142.  
  1143. (the bug is described in L<"BUGS">).  One can use this new interface as
  1144.  
  1145.   tie $a, 'symbolic', 3;
  1146.   tie $b, 'symbolic', 4;
  1147.   $a->nop;  $b->nop;    # Around a bug
  1148.  
  1149.   my $c = sqrt($a**2 + $b**2);
  1150.  
  1151. Now numeric value of $c is 5.  After C<$a = 12; $b = 5> the numeric value
  1152. of $c becomes 13.  To insulate the user of the module add a method
  1153.  
  1154.   sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
  1155.  
  1156. Now
  1157.  
  1158.   my ($a, $b);
  1159.   symbolic->vars($a, $b);
  1160.   my $c = sqrt($a**2 + $b**2);
  1161.  
  1162.   $a = 3; $b = 4;
  1163.   printf "c5  %s=%f\n", $c, $c;
  1164.  
  1165.   $a = 12; $b = 5;
  1166.   printf "c13  %s=%f\n", $c, $c;
  1167.  
  1168. shows that the numeric value of $c follows changes to the values of $a
  1169. and $b.
  1170.  
  1171. =head1 AUTHOR
  1172.  
  1173. Ilya Zakharevich E<lt>F<ilya@math.mps.ohio-state.edu>E<gt>.
  1174.  
  1175. =head1 DIAGNOSTICS
  1176.  
  1177. When Perl is run with the B<-Do> switch or its equivalent, overloading
  1178. induces diagnostic messages.
  1179.  
  1180. Using the C<m> command of Perl debugger (see L<perldebug>) one can
  1181. deduce which operations are overloaded (and which ancestor triggers
  1182. this overloading). Say, if C<eq> is overloaded, then the method C<(eq>
  1183. is shown by debugger. The method C<()> corresponds to the C<fallback>
  1184. key (in fact a presence of this method shows that this package has
  1185. overloading enabled, and it is what is used by the C<Overloaded>
  1186. function of module C<overload>).
  1187.  
  1188. =head1 BUGS
  1189.  
  1190. Because it is used for overloading, the per-package hash %OVERLOAD now
  1191. has a special meaning in Perl. The symbol table is filled with names
  1192. looking like line-noise.
  1193.  
  1194. For the purpose of inheritance every overloaded package behaves as if
  1195. C<fallback> is present (possibly undefined). This may create
  1196. interesting effects if some package is not overloaded, but inherits
  1197. from two overloaded packages.
  1198.  
  1199. Relation between overloading and tie()ing is broken.  Overloading is 
  1200. triggered or not basing on the I<previous> class of tie()d value.
  1201.  
  1202. This happens because the presence of overloading is checked too early, 
  1203. before any tie()d access is attempted.  If the FETCH()ed class of the
  1204. tie()d value does not change, a simple workaround is to access the value 
  1205. immediately after tie()ing, so that after this call the I<previous> class
  1206. coincides with the current one.
  1207.  
  1208. B<Needed:> a way to fix this without a speed penalty.
  1209.  
  1210. Barewords are not covered by overloaded string constants.
  1211.  
  1212. This document is confusing.  There are grammos and misleading language
  1213. used in places.  It would seem a total rewrite is needed.
  1214.  
  1215. =cut
  1216.  
  1217.